<template>
	<!-- 整体容器 -->
	<view class="container">
		<!-- 活动信息区域: 展示活动封面、标题、描述和状态 -->
		<view class="activity-info">
			<image :src="activityInfo.cover_image" mode="aspectFill" class="cover" @click="previewImage(activityInfo.cover_image)"></image>
			<view class="content">
				<text class="title">{{activityInfo.title}}</text>
				<text class="desc">{{activityInfo.description}}</text>
				<view class="meta">
					<text class="time">{{activityInfo.start_time}} - {{activityInfo.end_time}}</text>
					<text :class="['status', activityInfo.status]">{{activityInfo.status}}</text>
				</view>
			</view>
		</view>
		
		<!-- 奖励列表区域: 展示活动相关的奖励信息 -->
		<view class="reward-list">
			<view class="section-title">活动奖励</view>
			<!-- 有奖励时显示列表 -->
			<template v-if="rewardList.length > 0">
				<view v-for="item in rewardList" :key="item.id" class="reward-item">
					<image :src="item.image" mode="aspectFill" class="reward-img" @click="previewImage(item.image)"></image>
					<view class="info">
						<text class="name">{{item.reward_name}}</text>
						<text class="desc">{{item.description}}</text>
						<view class="meta">
							<text class="type">{{item.reward_type}}</text>
							<text :class="['quantity', item.remainingStatus]">
								剩余: {{item.remaining}}/{{item.quantity}}
								<text v-if="item.remainingStatus === 'low'" class="warning">即将抢完</text>
								<text v-if="item.remainingStatus === 'empty'" class="warning">已抢完</text>
							</text>
						</view>
					</view>
				</view>
			</template>
			<!-- 没有奖励时显示空状态 -->
			<view v-else class="empty-reward">
				<image :src="'/static/delault/empty.png'" mode="aspectFit" class="empty-icon"></image>
				<text class="empty-text">暂无奖励~ </text>
			</view>
		</view>
		
		<!-- 底部操作栏: 根据活动状态显示不同的操作按钮 -->
		<view class="action-bar" v-if="!isActivityEnded">
			<template v-if="hasParticipated">
				<view class="btn-group">
					<button class="btn complete" 
							:class="{ active: isCompleted }"
							@click="handleComplete(true)">
						已完成
					</button>
					<button class="btn incomplete" 
							:class="{ active: !isCompleted }"
							@click="handleComplete(false)">
						未完成
					</button>
				</view>
			</template>
			<button v-else 
					class="participate-btn" 
					@click="handleParticipate">
				立即参与
			</button>
		</view>
		
		<!-- 活动结束提示: 当活动结束时显示 -->
		<view class="end-tip" v-if="isActivityEnded">
			<text>你已经结束了本次活动</text>
		</view>
		
		<!-- 奖励选择弹窗 -->
		<view class="reward-modal" v-if="showRewardModal" @click.stop="closeRewardModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="title">选择奖励</text>
				</view>
				<view class="modal-body">
					<scroll-view scroll-y class="reward-list">
						<view v-for="item in availableRewards" 
							  :key="item.id" 
							  class="reward-item"
							  :class="{ active: selectedReward?.id === item.id }"
							  @click="selectReward(item)">
							<image :src="item.image" mode="aspectFill" class="reward-img"></image>
							<view class="info">
								<text class="name">{{item.reward_name}}</text>
								<text class="type">{{item.reward_type}}</text>
								<text class="quantity">剩余: {{item.remaining}}/{{item.quantity}}</text>
							</view>
							<text class="iconfont icon-check" v-if="selectedReward?.id === item.id"></text>
						</view>
					</scroll-view>
				</view>
				<view class="modal-footer">
					<button class="btn cancel" @click="closeRewardModal">取消</button>
					<button class="btn confirm" 
							:disabled="!selectedReward"
							@click="confirmComplete">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { api } from '@/utils/request'

// 页面状态管理
const activityId = ref(null)          // 活动ID
const activityInfo = ref({})          // 活动信息
const rewardList = ref([])            // 奖励列表
const hasParticipated = ref(false)    // 是否已参与
const isCompleted = ref(false)        // 是否已完成
const isActivityEnded = ref(false)    // 活动是否结束

// 奖励选择相关状态
const showRewardModal = ref(false)
const selectedReward = ref(null)
const availableRewards = computed(() => {
	return rewardList.value.filter(item => item.remaining > 0)
})

// ===== 本地存储相关函数 =====

/**
 * 检查本地存储中的参与记录
 * 依赖: 无
 * 被调用: checkParticipation
 */
const checkLocalParticipation = () => {
	const userInfo = uni.getStorageSync('userInfo')
	if (!userInfo) return false
	
	const participations = uni.getStorageSync('participations') || {}
	return participations[activityId.value] || {}
}

/**
 * 保存参与记录到本地存储
 * 依赖: checkLocalParticipation
 * 被调用: handleParticipate, handleComplete
 */
const saveParticipation = (isEnded = false) => {
	const userInfo = uni.getStorageSync('userInfo')
	if (!userInfo) return
	
	const participations = uni.getStorageSync('participations') || {}
	participations[activityId.value] = {
		participated: true,
		timestamp: new Date().toISOString(),
		isEnded: isEnded
	}
	
	uni.setStorageSync('participations', participations)
}

/**
 * 检查本地是否有活动结束记录
 * 依赖: checkLocalParticipation
 * 被调用: checkParticipationAndEnded
 */
const checkLocalActivityEnded = () => {
	const participation = checkLocalParticipation()
	return participation.isEnded || false
}

// ===== 工具函数 =====

/**
 * 处理图片URL,确保完整路径
 * 依赖: api.BASE_URL
 * 被调用: getActivityDetail, getRewardList
 */
const getFullImageUrl = (url) => {
	if(!url) return '/static/default.png'
	if(url.startsWith('http')) return url
	const BASE_URL = api.BASE_URL
	return BASE_URL + url
}

/**
 * 格式化时间显示
 * 依赖: 无
 * 被调用: getActivityDetail
 */
const formatTime = (timeStr) => {
	if (!timeStr) return ''
	return timeStr.replace('T', ' ').split('.')[0]
}

/**
 * 计算奖励剩余状态
 * 依赖: 无
 * 被调用: getRewardList
 */
const getRemainingStatus = (remaining, quantity) => {
	const ratio = remaining / quantity
	if (ratio <= 0) return 'empty'
	if (ratio <= 0.2) return 'low'
	return 'normal'
}

// ===== 数据映射 =====

// 奖励类型映射
const rewardTypeMap = {
	'physical': '实物',
	'points': '积分',
	'coupon': '优惠券'
}

// 默认空状态图片
const EMPTY_ICON = 'https://cdn.uviewui.com/uview/empty/data.png'

// ===== API请求函数 =====

/**
 * 获取活动详情
 * 依赖: api.request, getFullImageUrl, formatTime
 * 被调用: onMounted
 */
const getActivityDetail = async () => {
	try {
		const res = await api.request({
			url: '/api/activity/detail/',
			method: 'GET',
			data: {
				activity_id: activityId.value
			}
		})
		
		if(res.code === 200) {
			activityInfo.value = res.data
			activityInfo.value.cover_image = getFullImageUrl(res.data.cover_image)
			activityInfo.value.created_at = formatTime(res.data.created_at)
			activityInfo.value.updated_at = formatTime(res.data.updated_at)
			
			const statusMap = {
				'draft': '草稿',
				'published': '已发布',
				'ended': '已结束'
			}
			activityInfo.value.status = statusMap[res.data.status] || res.data.status
		}
	} catch(e) {
		console.error(e)
		uni.showToast({
			title: '获取活动信息失败',
			icon: 'none'
		})
	}
}

/**
 * 获取奖励列表
 * 依赖: api.request, getFullImageUrl, rewardTypeMap, getRemainingStatus
 * 被调用: onMounted
 */
const getRewardList = async () => {
	try {
		const res = await api.request({
			url: '/api/reward/list/' + activityId.value + "/",
			method: 'GET'
		})
		
		if(res.code === 200) {
			rewardList.value = (res.data || []).map(item => ({
				...item,
				image: getFullImageUrl(item.image),
				reward_type: rewardTypeMap[item.reward_type] || item.reward_type,
				remainingStatus: getRemainingStatus(item.remaining, item.quantity)
			}))
		}
	} catch(e) {
		console.error(e)
		uni.showToast({
			title: '获取奖励列表失败',
			icon: 'none'
		})
	}
}

// ===== 交互处理函数 =====

/**
 * 处理参与活动
 * 依赖: api.request, saveParticipation
 * 被调用: 模板点击事件
 */
const handleParticipate = async () => {
	try {
		const userInfo = uni.getStorageSync('userInfo')
		if(!userInfo) {
			uni.navigateTo({
				url: '/pages/user/login'
			})
			return
		}
		
		const res = await api.request({
			url: '/api/participate/',
			method: 'POST',
			data: {
				user_id: userInfo.user_id,
				activity_id: activityId.value
			}
		})
		
		if(res.code === 200) {
			hasParticipated.value = true
			saveParticipation()
			uni.showToast({
				title: '参与成功',
				icon: 'success'
			})
		} else {
			uni.showToast({
				title: res.message || '参与失败',
				icon: 'none'
			})
		}
	} catch(e) {
		console.error(e)
		uni.showToast({
			title: '参与失败',
			icon: 'none'
		})
	}
}

/**
 * 检查参与状态
 * 依赖: api.request, checkLocalParticipation, saveParticipation, checkParticipationAndEnded
 * 被调用: onMounted
 */
const checkParticipation = async () => {
	try {
		const userInfo = uni.getStorageSync('userInfo')
		if(!userInfo) return
		
		const localParticipation = checkLocalParticipation()
		if (localParticipation.participated) {
			hasParticipated.value = true
			if(localParticipation.isEnded) {
				isActivityEnded.value = true
				return
			}
			await checkParticipationAndEnded()
			return
		}
		
		const res = await api.request({
			url: '/api/activity/is_participated/',
			method: 'GET',
			data: {
				user_id: userInfo.user_id,
				activity_id: activityId.value
			}
		})
		if(res.code === 200) {
			hasParticipated.value = res.data
			if (res.data) {
				saveParticipation()
				await checkParticipationAndEnded()
			}
		}
	} catch(e) {
		console.error(e)
	}
}

/**
 * 图片预览处理
 * 依赖: uni.previewImage
 * 被调用: 模板点击事件
 */
const previewImage = (url) => {
	if(!url) return
	
	const urls = []
	
	if(activityInfo.value.cover_image) {
		urls.push(activityInfo.value.cover_image)
	}
	
	rewardList.value.forEach(item => {
		if(item.image) {
			urls.push(item.image)
		}
	})
	
	if(urls.length === 0) return
	
	const current = urls.indexOf(url)
	
	uni.previewImage({
		urls: urls,
		current: current,
		indicator: 'number',
		loop: true,
		longPressActions: {
			itemList: ['发送给朋友', '保存图片', '收藏'],
			success: function(data) {
				console.log('选中了第' + (data.tapIndex + 1) + '个按钮');
			},
			fail: function(err) {
				console.log(err.errMsg);
			}
		},
		success: () => {
			console.log('预览图片成功');
		},
		fail: (err) => {
			console.error('预览图片失败：', err);
			uni.showToast({
				title: '预览图片失败',
				icon: 'none'
			});
		}
	});
}

/**
 * 检查参与和结束状态
 * 依赖: api.request, checkLocalActivityEnded, saveParticipation
 * 被调用: checkParticipation
 */
const checkParticipationAndEnded = async () => {
	try {
		const userInfo = uni.getStorageSync('userInfo')
		if(!userInfo) return
		
		if(checkLocalActivityEnded()) {
			isActivityEnded.value = true
			return
		}
		
		const res = await api.request({
			url: '/api/participation/is_participated_and_ended/',
			method: 'GET',
			data: {
				user_id: userInfo.user_id,
				activity_id: activityId.value
			}
		})
		
		if(res.code === 200) {
			isActivityEnded.value = res.data
			if(res.data) {
				saveParticipation(true)
				uni.showToast({
					title: '你已经结束了本次活动',
					icon: 'none',
					duration: 2000
				})
			}
		}
	} catch(e) {
		console.error(e)
	}
}

/**
 * 处理完成活动
 * 依赖: api.request, saveParticipation
 * 被调用: 模板点击事件
 */
const handleComplete = async (isComplete) => {
	if (isComplete) {
		// 如果已经完成过活动，不再弹出奖励菜单
		if (isCompleted.value) {
			uni.showToast({
				title: '已经完成过该活动',
				icon: 'none'
			})
			return
		}
		
		// 如果是完成操作,先检查是否有可用奖励
		if (availableRewards.value.length === 0) {
			uni.showToast({
				title: '暂无可用奖励',
				icon: 'none'
			})
			return
		}
		// 显示奖励选择弹窗
		showRewardModal.value = true
		return
	}
	
	// 取消完成的逻辑保持不变
	uni.showModal({
		title: '取消完成',
		content: '确定将活动标记为未完成？',
		success: async (res) => {
			if (res.confirm) {
				await submitComplete(false)
			}
		}
	})
}

// 选择奖励
const selectReward = (reward) => {
	selectedReward.value = reward
}

// 关闭奖励选择弹窗
const closeRewardModal = () => {
	showRewardModal.value = false
	selectedReward.value = null
}

// 确认完成并提交选择的奖励
const confirmComplete = async () => {
	if (!selectedReward.value) {
		uni.showToast({
			title: '请选择奖励',
			icon: 'none'
		})
		return
	}
	
	// 显示确认提示
	uni.showModal({
		title: '提交确认',
		content: '请确保您在个人资料中填写了正确的联系方式，管理员会在1天内完成审核并发放奖励。是否确认提交？',
		success: async (res) => {
			if (res.confirm) {
				await submitComplete(true, selectedReward.value.id)
				closeRewardModal()
			}
		}
	})
}

// 提交完成状态
const submitComplete = async (isComplete, rewardId = null) => {
	try {
		const userInfo = uni.getStorageSync('userInfo')
		if(!userInfo) {
			uni.navigateTo({
				url: '/pages/user/login'
			})
			return
		}
		
		const res = await api.request({
			url: '/api/complete/',
			method: 'POST',
			data: {
				user_id: userInfo.user_id,
				activity_id: activityId.value,
				is_complete: isComplete,
				reward_id: rewardId
			}
		})
		
		if(res.code === 200) {
			isCompleted.value = isComplete
			if(isComplete) {
				saveParticipation(true)
				await getRewardList()
				// 提交成功后显示等待审核提示
				uni.showModal({
					title: '提交成功',
					content: '您的完成状态已提交。管理员将在1天内完成审核，请确保您的联系方式正确，以便及时接收奖励。',
					showCancel: false
				})
			}
			uni.showToast({
				title: isComplete ? '已完成活动' : '已取消完成',
				icon: 'success'
			})
		} else {
			uni.showToast({
				title: res.message || '操作失败',
				icon: 'none'
			})
		}
	} catch(e) {
		console.error(e)
		uni.showToast({
			title: '操作失败',
			icon: 'none'
		})
	}
}

// 页面加载时初始化
onMounted(() => {
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	activityId.value = currentPage.options.id
	
	if(activityId.value) {
		getActivityDetail()
		getRewardList()
		checkParticipation()
	}
})
</script>

<style lang="scss" scoped>
.container {
	padding-bottom: 120rpx;
	
	.activity-info {
		.cover {
			width: 100%;
			height: 400rpx;
			&:active {
				opacity: 0.8;
			}
		}
		
		.content {
			padding: 30rpx;
			background: #fff;
			
			.title {
				font-size: 36rpx;
				font-weight: bold;
			}
			
			.desc {
				font-size: 28rpx;
				color: #666;
				margin: 20rpx 0;
                // 独占一行
                display: block;
			}
			
			.meta {
				display: flex;
				justify-content: space-between;
				font-size: 24rpx;
				color: #999;
			}
		}
	}
	
	.reward-list {
		margin-top: 20rpx;
		padding: 30rpx;
		background: #fff;
		
		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			margin-bottom: 20rpx;
		}
		
		.reward-item {
			display: flex;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #eee;
			
			.reward-img {
				width: 120rpx;
				height: 120rpx;
				border-radius: 12rpx;
				margin-right: 20rpx;
				flex-shrink: 0;
				&:active {
					opacity: 0.8;
				}
			}
			
			.info {
				flex: 1;
				display: flex;
				flex-direction: column;
				
				.name {
					font-size: 28rpx;
					font-weight: bold;
					margin-bottom: 8rpx;
				}
				
				.desc {
					font-size: 24rpx;
					color: #666;
					margin-bottom: 12rpx;
				}
				
				.meta {
					display: flex;
					justify-content: space-between;
					align-items: center;
					
					.type {
						font-size: 24rpx;
						color: #007AFF;
						background: rgba(0,122,255,0.1);
						padding: 4rpx 12rpx;
						border-radius: 4rpx;
					}
					
					.quantity {
						font-size: 24rpx;
						color: #999;
						
						&.low {
							color: #ff6b6b;
							
							.warning {
								margin-left: 8rpx;
								font-size: 20rpx;
								background: #fff0f0;
								color: #ff6b6b;
								padding: 2rpx 8rpx;
								border-radius: 4rpx;
							}
						}
						
						&.empty {
							color: #999;
							
							.warning {
								margin-left: 8rpx;
								font-size: 20rpx;
								background: #f5f5f5;
								color: #999;
								padding: 2rpx 8rpx;
								border-radius: 4rpx;
							}
						}
						
						&.normal {
							color: #67c23a;
						}
					}
				}
			}
		}
		
		.empty-reward {
			padding: 60rpx 0;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			
			.empty-icon {
				width: 200rpx;
				height: 200rpx;
				margin-bottom: 20rpx;
			}
			
			.empty-text {
				font-size: 28rpx;
				color: #999;
			}
		}
	}
	
	.action-bar {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 20rpx;
		background: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
		
		.btn-group {
			display: flex;
			gap: 20rpx;
			
			.btn {
				flex: 1;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 40rpx;
				font-size: 32rpx;
				color: #666;
				background: #f5f5f5;
				
				&.complete {
					&.active {
						background: #52c41a;
						color: #fff;
					}
				}
				
				&.incomplete {
					&.active {
						background: #ff6b6b;
						color: #fff;
					}
				}
			}
		}
		
		.participate-btn {
			width: 100%;
			height: 80rpx;
			line-height: 80rpx;
			background: #007AFF;
			color: #fff;
			border-radius: 40rpx;
			font-size: 32rpx;
			
			&:disabled {
				background: #ccc;
			}
		}
	}
	
	.end-tip {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 20rpx;
		background: #f5f5f5;
		text-align: center;
		color: #999;
		font-size: 28rpx;
	}
}

/* 奖励选择弹窗样式 */
.reward-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.6);
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;
	
	.modal-content {
		width: 600rpx;
		background: #fff;
		border-radius: 20rpx;
		overflow: hidden;
		
		.modal-header {
			padding: 30rpx;
			text-align: center;
			border-bottom: 1rpx solid #eee;
			
			.title {
				font-size: 32rpx;
				font-weight: bold;
			}
		}
		
		.modal-body {
			max-height: 600rpx;
			
			.reward-list {
				max-height: 600rpx;
				
				.reward-item {
					display: flex;
					align-items: center;
					padding: 20rpx;
					border-bottom: 1rpx solid #eee;
					position: relative;
					
					&.active {
						background: #f0f9ff;
					}
					
					.reward-img {
						width: 100rpx;
						height: 100rpx;
						border-radius: 10rpx;
						margin-right: 20rpx;
					}
					
					.info {
						flex: 1;
						
						.name {
							font-size: 28rpx;
							font-weight: bold;
							margin-bottom: 10rpx;
						}
						
						.type {
							font-size: 24rpx;
							color: #666;
							margin-bottom: 6rpx;
						}
						
						.quantity {
							font-size: 24rpx;
							color: #999;
						}
					}
					
					.icon-check {
						position: absolute;
						right: 20rpx;
						color: #007AFF;
						font-size: 40rpx;
					}
				}
			}
		}
		
		.modal-footer {
			display: flex;
			padding: 20rpx;
			gap: 20rpx;
			
			.btn {
				flex: 1;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				font-size: 28rpx;
				border-radius: 40rpx;
				
				&.cancel {
					background: #f5f5f5;
					color: #666;
				}
				
				&.confirm {
					background: #007AFF;
					color: #fff;
					
					&:disabled {
						opacity: 0.5;
					}
				}
			}
		}
	}
}
</style> 